<template>
    <div class="form-page">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="旧密码" prop="oldPassword">
                <PasswordInput v-model="form.oldPassword" placeholder="旧密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <PasswordInput v-model="form.newPassword" placeholder="新密码" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
                <PasswordInput v-model="form.confirmPassword" placeholder="确认密码" />
            </el-form-item>
            <el-form-item>
                <AsyncButton class="submit-btn" :loading="loading" type="primary" @click="submitForm(formRef)">
                    确定
                </AsyncButton>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { updateMyPassword, refreshToken } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store'
import PasswordInput from '@/components/passwordInput/index.vue'

const form = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
});

const rules = {
    oldPassword: [
        { required: true, message: '请输入旧密码' },
    ],
    newPassword: [
        { required: true, message: '请输入新密码' },
    ],
    confirmPassword: [
        { required: true, message: '请输入确认密码' },
        { validator: validatePassword },
    ],
}

const formRef = ref(null);

const loading = ref(false)

function submitForm(formRef) {
    formRef.validate(valid => {
        if (valid) {
            loading.value = true
            updateMyPassword(form.value).then(res => {
                console.log(res, 'res')
                loading.value = false
                if (res.code === 200) {
                    ElMessage.success(res.msg)
                } else {
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                loading.value = false
            })
        }
    });
}

function validatePassword(rule, value, callback){
    if(value === '') {
        callback(new Error('请输入确认密码'))
    }else if(value !== form.value.newPassword){
        callback(new Error('确认密码不一致'))
    }else {
        callback()
    }
}
</script>

<style lang="scss">
@import '@/assets/css/form-page.scss';
</style>